#!/usr/bin/env python

# TODO: change variables i and wordLen to short instead of int
# TODO: support for case-sensitive and insensitive searching

"fgrepwc.py -- searches for string in text file, displays matching lines and counts number of matches"

import sys
import string

# print usage and exit
def usage():
    print "usage:	fgrepwc [-i] string file"
    sys.exit(1)

# count number of substring matches in a line
def substrc(word, line):

    # set cursor i to the start
    i = 0

    # number of matches in line
    linec = 0

    # assign length of the word to a variable
    wordLen = len(word)

    while i + wordLen <= len(line) :
        if word[0] == line[i] and word == line[i:wordLen+i] :
            linec = linec + 1
            i = i + wordLen
        else:
            i = i + 1

    return linec

# opens the file and searches for match per line; calls substrc
def filefind(word, filename, caseSens=True):

#    print caseSens
    # reset word count
    count = 0

    # can we open file? if so, return file handle
    try:
        fh = open(filename, 'r')
        fileOpened = 1

    # if not, exit
    except:
        print filename, ":", sys.exc_info()[1]
        usage()

    if fileOpened == 1:
        # read all file lines into list and close
        allLines = fh.readlines()
        fh.close()

        # iterate over all lines of file
        for eachLine in allLines:

            # search each line for the word
            # if string.find(eachLine, word) > -1: # old condition
            if not caseSens and word.lower() in eachLine.lower() or caseSens and word in eachLine:
                count = count + substrc(word, eachLine)
                print eachLine,

        # when complete, substring count
        print count

# validates arguments and calls filefind()
def checkargs():

    caseSens = True
    # argument index
    i = 1
    # check args; 'argv' comes from 'sys' module
    argc = len(sys.argv)
    if argc < 3 or argc > 4:
        usage()
    elif argc == 4:
        if sys.argv[1] == "-i":
            i = i + 1
            caseSens = False
        else:
            usage()

    print caseSens;
    # call fgrepwc.filefind() with args
    filefind(sys.argv[i], sys.argv[i+1], caseSens)

# execute as application as stand alone
if __name__ == '__main__':
    checkargs()
